package com.warrior.superdata.dds.datasource;

import com.zaxxer.hikari.HikariDataSource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 数据源连接超时操作类
 */
@Slf4j
@Data
public class DDSTimer {
    /**
     * 默认超时时间
     */
    private static long idel = 5 * 60 * 1000;

    private HikariDataSource dataSource;
    private long lastUpdateTime = 0L;

    /**
     * 构造函数
     * @param newDataSource
     */
    public DDSTimer(HikariDataSource newDataSource) {
        this.dataSource = newDataSource;
        this.lastUpdateTime = System.currentTimeMillis();
    }

    /**
     * 刷新更新时间
     */
    public void refreshTime() {
        lastUpdateTime = System.currentTimeMillis();
    }

    /**
     * 检查超时连接并关闭
     * @return
     */
    public boolean checkAndClose() {
        if (isTimeout()) {
            dataSource.close();
            return true;
        }
        //清除ThreadLocal
        DBIdentifier.remove();
        return false;
    }

    /**
     * 判断是否超时
     * @return
     */
    private boolean isTimeout() {
        return (System.currentTimeMillis() - lastUpdateTime) > idel;
    }
}
